package com.gadgets.cm01.user.service.impl;

import com.gadgets.cm01.common.GadgetsCm01ExceptionConstant;
import com.gadgets.cm01.user.dto.UserInfoOperationDTO;
import com.gadgets.cm01.user.dto.UserInfoQueryDTO;
import com.gadgets.cm01.user.dto.UserLoginDTO;
import com.gadgets.cm01.user.pojo.User;
import com.gadgets.cm01.user.repository.IUserRepository;
import com.gadgets.cm01.user.service.IUserLoginService;
import com.gadgets.framework.common.exception.GadgetsException;
import com.gadgets.framework.common.exception.GadgetsServiceException;
import com.gadgets.framework.common.exception.GadgetsValidateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author UncleXiu
 * @version V1.0.0
 * @data 2020-09-17
 * 
 */
@Service
@Transactional(transactionManager = "gadgetsDbTransactionManage", rollbackFor = Throwable.class)
public class UserLoginServiceImpl implements IUserLoginService {

    @Autowired
    private IUserRepository userRepository;

    /**
     * 用户登录
     *
     * @param request      请求信息
     * @param response     应答信息
     * @param userLoginDTO 用户登录信息
     *
     * @throws GadgetsValidateException 校验信息
     */
    @Transactional(transactionManager = "gadgetsDbTransactionManage", rollbackFor = Throwable.class)
    @Override
    public User loginIn(HttpServletRequest request, HttpServletResponse response, UserLoginDTO userLoginDTO) throws GadgetsValidateException {
        UserInfoQueryDTO queryDTO = new UserInfoQueryDTO();
        queryDTO.setUserNo(userLoginDTO.getUserNo());
        queryDTO.setUserName(userLoginDTO.getUserName());
        List<User> users = userRepository.selectUserInfoByCondition(queryDTO,null);
        if(users.size()==1){
            return users.get(0);
        }else {
            // 根据用户号没有查询到信息，直接抛出异常
            throw new GadgetsServiceException(GadgetsCm01ExceptionConstant.USER_LOGIN_INFO_ERRROR,new Object[]{});
        }
    }

    /**
     * 更新用户密码错误次数
     *
     * @param user 用户信息
     *
     * @throws GadgetsException 异常信息
     */
    @Transactional(transactionManager = "gadgetsDbTransactionManage", rollbackFor = Throwable.class)
    @Override
    public void updateUserPwdTm(UserInfoOperationDTO user) throws GadgetsException {
        // 增加错误次数，数据库有触发器，如果增加错误次数以后已达到冻结的标准，则自动冻结用户
        userRepository.updateUserStatusInfo(user);
    }

}
